package com.presto.directo.net

import android.os.Build
import android.provider.Settings
import com.presto.directo.base.XApplication
import com.presto.directo.net.CipherUtil.ecodeByMD5
import com.presto.directo.net.CipherUtil.getCipher
import com.presto.directo.utils.*
import java.util.*

object SignUtil {
    const val key = "234dfsdfdf334df32233333;343g44gsdfsdfgwerwerwer"
    fun createClientSignV4(paramsTreeMap: SortedMap<String, Any?>?): String? {
        var sign: String? = ""
        val buffer = StringBuilder()
        if (null != paramsTreeMap) { // 遍历添加所有传值
            for (key in paramsTreeMap.keys) {
                val value = paramsTreeMap[key]
                if (null != value) {
                    if (value is String) {
                        buffer.append(value)
                    } else if (value is Boolean) {
                        buffer.append(value.toString())
                    } else if (value is Int) {
                        buffer.append(value.toString())
                    } else if (value is Double) {
                        buffer.append(value.toString())
                    } else if (value is Float) {
                        buffer.append(value.toString())
                    } else if (value is Long) {
                        buffer.append(value.toString())
                    } else if (value is Short) {
                        buffer.append(value.toString())
                    }
                }
            }
            // 添加一级签名
            buffer.append(getCipher())
        }
        // md5一级签名
        sign = ecodeByMD5(buffer.toString())
        // md5二级签名
        sign = ecodeByMD5(sign + key.split(";")[1])
        return sign
    }

}

fun MutableMap<String, Any?>.sign(messageId: Int): MutableMap<String, Any?> {
    if (UserUtil.isLogin()) {
        put("user_id", UserUtil.getUserId())
    }
    put(
        "android_id", try {
            Settings.System.getString(XApplication.application.contentResolver, Settings.Secure.ANDROID_ID)
        } catch (e: Exception) {
            ""
        }
    )
    put("appsflyer_device_id", Af.getAfId())
    put("pkg_name", XApplication.application.packageName)
    put("package_name", XApplication.application.packageName)
    put("app_version", XApplication.application.getAppVersion())
    put("version", "Android" + Build.VERSION.RELEASE)
    put("channel", "999")
    put("timestamp", System.currentTimeMillis().toString())
    put("androidIos", "2")
    put("message_id", messageId)
    put("sign", SignUtil.createClientSignV4(TreeMap(this)))
    return this
}

fun getHttpMap(): MutableMap<String, Any?> {
    return mutableMapOf()
}